#!/usr/bin/env python3
import http.server
import socketserver
import json
import hashlib
import datetime
import urllib.parse
from io import BytesIO

class DeviceRegistrationHandler(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        # 获取POST请求的内容长度
        content_length = int(self.headers['Content-Length'])
        # 读取POST数据
        post_data = self.rfile.read(content_length)
        
        try:
            # 解析JSON数据
            request_data = json.loads(post_data.decode('utf-8'))
            
            # 提取所需字段
            dev_id = request_data.get('dev_id', '')
            dev_ser = request_data.get('dev_ser', {})
            cpu_ser = dev_ser.get('cpu_ser', '')
            
            # 验证设备ID是否由CPU序列号加盐后取MD5值生成
            expected_cpu_serial_with_salt = f"{cpu_ser}&fangchao#"
            expected_dev_id = hashlib.md5(expected_cpu_serial_with_salt.encode()).hexdigest()
            
            # 准备响应数据
            response_data = {
                "dev_id": dev_id,
                "event_time": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
            
            # 验证设备ID
            if dev_id == expected_dev_id:
                response_data["respond"] = "factory_activated"
                status_code = 200
            else:
                response_data["respond"] = "factory_activation_failed"
                response_data["error"] = "Invalid device ID"
                status_code = 400
            
            # 发送响应
            response_json = json.dumps(response_data)
            self.send_response(status_code)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(response_json.encode('utf-8'))
            
            # 打印请求和响应信息（用于调试）
            print(f"收到请求: {request_data}")
            print(f"发送响应: {response_data}")
            
        except json.JSONDecodeError:
            self.send_error(400, "Invalid JSON")
        except Exception as e:
            self.send_error(500, f"Server error: {str(e)}")

def run_server(port=8888):
    with socketserver.TCPServer(("", port), DeviceRegistrationHandler) as httpd:
        print(f"设备注册服务器启动在端口 {port}...")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("服务器已停止")
            httpd.server_close()

if __name__ == "__main__":
    run_server()
